package com.example.testone

import android.content.res.Resources
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.AdaptScreenUtils
import com.example.testone.databinding.ActivityMainBinding
import com.example.testone.utils.*
import com.example.testone.viewModels.SettingViewModel
import dagger.hilt.android.AndroidEntryPoint
import me.f1reking.serialportlib.SerialPortHelper
import me.f1reking.serialportlib.listener.IOpenSerialPortListener
import me.f1reking.serialportlib.listener.ISerialPortDataListener
import me.f1reking.serialportlib.listener.Status
import java.io.File
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import javax.inject.Inject


@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"
    val VIEW_MODEL_TAG = "VIEW_MODEL_TAG"
    lateinit var binding: ActivityMainBinding
    @Inject
    lateinit var usbPermission: UsbPermission
//    @Inject
//    lateinit var serialPortUtil: SerialPortUtils
    @Inject
    lateinit var deviceProtocol: DeviceProtocol
    @Inject
    lateinit var mySerialPort: MySerialPort

    val viewModel: SettingViewModel by viewModels()


    private val mExecutorTask: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()

    override fun onCreate(savedInstanceState: Bundle?) {


        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
        setContentView(binding.root)

        viewModelEvent()
        //任务信息
        initTask()

    }


    private fun viewModelEvent() {

        //UV查杀状态
        viewModel.countdownIsRunning.observe(this,object : Observer<Int> {
            override fun onChanged(t: Int?) {
                if(t==null || t<0) return
                if ( viewModel.isOpening.value == false ) {
                    deviceProtocol.command(0x20,0x21, byteArrayOf(0x1E,0x3C,0x00))
                    viewModel.settingRunningState.value = -1 //恢复初始化
                } else {
                    if ( t==1 ) { //运行中
                        deviceProtocol.command(0x30,0x31, byteArrayOf(0x00,0x00,0x00))
                    } else if( t==2 ) { //已暂停
                        deviceProtocol.command(0x30,0x32, byteArrayOf(0x00,0x00,0x00))
                    } else if( t==0 ) { //已停止
                        deviceProtocol.command(0x30,0x32, byteArrayOf(0x00,0x00,0x00))
                    }
                }

            }


        })
        //开机
        viewModel.bootState.observe(this){
            if(it<0) return@observe
            //开机
            deviceProtocol.command(0x20,0x21, byteArrayOf(0x1E,0x3C,0x00))
            viewModel.isBootState.value = true
        }
        //运行状态
        viewModel.settingRunningState.observe(this){
            if(it<0) return@observe
            MyLog.print(VIEW_MODEL_TAG, "-----settingRunningState---${it}---isOpening--${viewModel.isOpening.value}---isBootState:${viewModel.isBootState.value}")

//            sendData(viewModel.currentBtn,"settingRunningState", it)
            when(it){
                1 -> { //开始
                    //检测开机状态
                    if ( viewModel.isBootState.value == false ) {
                        deviceProtocol.command(0x20,0x21, byteArrayOf(0x1E,0x3C,0x00))
                        viewModel.isBootState.value = true
//                        viewModel.settingRunningState.value = 1 //恢复初始化
                    }else{
                        viewModel.isWorking.value = true
                        //开始工作
//                        DeviceFlow.sendData("","WORK" )
                        deviceProtocol.command(0x20,0x28, byteArrayOf(0x00,0x00,0x00))
                        //初始化温度
//                        DeviceFlow.sendData("init","wdSetting",viewModel.wdSetting.value!!)
//                        deviceProtocol.command(0x20,0x23, byteArrayOf(viewModel.wdSetting.value!!.toByte(),0x00,0x00))
                        //初始化时间
//                        DeviceFlow.sendData("init","timeSetting",viewModel.timeSetting.value!!)
//                        DeviceProtocol.command(0x20,0x24, byteArrayOf((viewModel.countdownTime.value!!+SettingViewModel.BOX_UP_MINUTE).toByte(),0x00,0x00))
                    }

                }
                2 -> { //暂停
                    viewModel.isWorking.value = false
                    //开始工作
//                    DeviceFlow.sendData("","STOP" )
                    deviceProtocol.command(0x20,0x29, byteArrayOf(0x00,0x00,0x00))
                }
                0 -> { //停止
                    //停止工作
                    viewModel.isWorking.value = false
//                    viewModel.isBootState = false
                    //停止工作
                    deviceProtocol.command(0x20,0x29, byteArrayOf(0x00,0x00,0x00))
                }
            }
        }

        //设置时间
        viewModel.countdownTime.observe(this){
            if(it<0) return@observe
            MyLog.print(VIEW_MODEL_TAG, "-----countdownTime---${it}")
            //发送数据
            deviceProtocol.command(0x20,0x24, byteArrayOf((viewModel.countdownTime.value!!+SettingViewModel.BOX_UP_MINUTE).toByte(),0x00,0x00))

        }
//        //设置温度
        viewModel.wdSetting.observe(this){
            if(it<0) return@observe
            MyLog.print(VIEW_MODEL_TAG, "-----wdSetting---${it}")
            deviceProtocol.command(0x20,0x23, byteArrayOf(viewModel.wdSetting.value!!.toByte(),0x00,0x00))
        }
        //声音
        viewModel.voiceNumber.observe(this){
            if(it<0) return@observe
            MyLog.print(VIEW_MODEL_TAG, "-----voiceNumber---${it}")
        }
        //灯光
        viewModel.lightNumber.observe(this){
            if(it<0) return@observe
            MyLog.print(VIEW_MODEL_TAG, "-----lightNumber---${it}")
            deviceProtocol.command(0x20,0x2E, byteArrayOf(viewModel.lightNumber.value!!.toByte(),0x00,0x00))

        }
        //当前温度
        viewModel.wdNumber.observe(this){
            if(it<0) return@observe
            MyLog.print(VIEW_MODEL_TAG, "-----wdNumber---${it}")
        }

    }


    //初始化task任务
    fun initTask(){
        mySerialPort.serialPort.setIOpenSerialPortListener(object :IOpenSerialPortListener{
            override fun onSuccess(device: File?) {
                viewModel.isOpening.postValue(true)
//                viewModel.isOpening.value = true
                MyLog.print("iOpenSerialPortListener", "onSuccess-${device}")
            }

            override fun onFail(device: File?, status: Status?) {
                viewModel.isOpening.postValue(false)
//                viewModel.isOpening.value = false
                MyLog.print("iOpenSerialPortListener", "onFail-${device}-${status}")
            }
        })

        mySerialPort.serialPort.setISerialPortDataListener(object: ISerialPortDataListener {
            override fun onDataReceived(bytes: ByteArray?) {
                //证明开机状态
                viewModel.isOpening.postValue(true)
                //更新发送时间
                viewModel.checkRecOpenTime = Helper.getCurrentTimeStamp()
                if(bytes!=null){
                    MyLog.print("iSerialPortDataListener", "size:${bytes.size}-code:${ByteUtil.toHexStr(bytes)}")
                    var new_data = arrayListOf<Byte>()
                    for((i,value) in bytes.withIndex()){
                        new_data.add(value)
                        if ( new_data.size % 6 == 0 ) {
                            val (maskIntro:MaskIntro?,protocol:ProtocolIntro?)=deviceProtocol.getModeObj(new_data[0],new_data[1])
                            Log.e("deviceCommandRec","接收:-${maskIntro?.name}->:${maskIntro?.code}->:${protocol?.name}->:${protocol?.code}--data:${ByteUtil.toHexStr(new_data.toByteArray())}")
                            if(protocol!=null){
                                protocol.command(viewModel ,new_data[0],new_data[1],new_data[2],new_data[3],new_data[4])
                            }else{
                                deviceProtocol.speCommand(viewModel ,new_data[0],new_data[1],new_data[2],new_data[3],new_data[4])
                            }
                            new_data.clear()
                        }
                    }
                }
            }

            override fun onDataSend(bytes: ByteArray?) {
                MyLog.print("iSerialPortDataListener", "onDataSend-${bytes?.let {
                    ByteUtil.toHexStr(
                        it
                    )
                }}")
            }


        })
//        处理消息机制
//        serialPortUtil.serialCallBackEvent = object :SerialCallBackEvent{
//            override fun callbackData(bytes: ByteArray) {
//                //证明开机状态
//                viewModel.isOpening = true
//                MyLog.print("serialCallBackEvent", "size:${bytes.size}-code:${ByteUtil.toHexStr(bytes)}")
//                var new_data = arrayListOf<Byte>()
//                for((i,value) in bytes.withIndex()){
//                    new_data.add(value)
//                    if ( new_data.size % 6 == 0 ) {
//                        val (maskIntro:MaskIntro?,protocol:ProtocolIntro?)=deviceProtocol.getModeObj(new_data[0],new_data[1])
//                        Log.e("output","接收:-${maskIntro?.name}->:${maskIntro?.code}->:${protocol?.name}->:${protocol?.code}--data:${ByteUtil.toHexStr(new_data.toByteArray())}")
//                        if(protocol!=null){
//                            protocol.command(viewModel ,new_data[0],new_data[1],new_data[2],new_data[3],new_data[4])
//                        }else{
//                            deviceProtocol.speCommand(viewModel ,new_data[0],new_data[1],new_data[2],new_data[3],new_data[4])
//                        }
//                        new_data.clear()
//                    }
//                }
//            }
//
//        }

        //开启定时线程
//        mExecutorTask.scheduleAtFixedRate(Runnable {
//
//
//
//
//
//        },0,5, TimeUnit.SECONDS)

        Timer().schedule(object: TimerTask(){
            override fun run() {
                runTask()
            }
        },Date(),5000)

    }


    private fun runTask()
    {
        MyLog.print(VIEW_MODEL_TAG, "-----isOpening:${viewModel.isOpening.value}--isWorking-${viewModel.isWorking.value}--isBootState-${viewModel.isBootState.value}")
        //是否处于通信状态-

        if(viewModel.isOpening.value==true){
            //查询开机状态指定
            if(viewModel.isBootState.value==true){
                if ( viewModel.checkSendBootTime - viewModel.checkRecBootTime > 20 ) {
                    //未处于开机状态
                    viewModel.isBootState.postValue(false)
                }
                //更新发送时间
                viewModel.checkSendBootTime = Helper.getCurrentTimeStamp()
            }



            //验证是否处于工作状态-查看工作状态
            if(viewModel.isWorking.value==true){
                if(viewModel.checkRecWorkTime >0 && viewModel.checkSendWorkTime - viewModel.checkRecWorkTime > 20){
                    //判定硬件未处于工作状态
                    viewModel.isWorking.postValue(false)

                    viewModel.settingRunningState.postValue(0)
                }
                //更新发送时间
                viewModel.checkSendWorkTime = Helper.getCurrentTimeStamp()

                //查询设置的温度值
                deviceProtocol.command(0x70,0x74, byteArrayOf(0x00,0x00,0x00))
            }
            //查询开机信息
            if(viewModel.checkSendOpenTime - viewModel.checkRecOpenTime > 15){
                //判定硬件未处于工作状态
                viewModel.isOpening.postValue(false)
            }
            //更新发送时间
            viewModel.checkSendOpenTime = Helper.getCurrentTimeStamp()
            //工作状态
            deviceProtocol.command(0x70,0x72, byteArrayOf(0x00,0x00,0x00))
        } else {
            //还没有通信 直接 断开协议重连
            mySerialPort.resetConn()
            //开机状态
            deviceProtocol.command(0x70,0x71, byteArrayOf(0x00,0x00,0x00))
        }
        deviceProtocol.command(0x10,0x08, byteArrayOf(0x00,0x00,0x00))
        //获取当前温度
//                if(viewModel.settingRunningState.value==1){ //正在运行
//                    DeviceProtocol.command(0x70,0x73, byteArrayOf(0x00,0x00,0x00))
//                    if(viewModel.isWorking.value==false){ //异常原因导致没有工作
//                        //执行工作
//                        DeviceProtocol.command(0x20,0x28, byteArrayOf(0x00,0x00,0x00))
//                    }
//                }

        //检测设定的温度值
    }

    override fun getResources(): Resources {
        return AdaptScreenUtils.adaptWidth(super.getResources(), 1280)

    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Toast.makeText(this@MainActivity, "·µ»Ø¼üÒÑ±»½ûÓÃ...", Toast.LENGTH_SHORT)
//                .show()
            return true // return true 和 false 我都试过，都能屏蔽，原因还未知，希望知道的可以告诉我一下，谢谢
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
//        super.onWindowFocusChanged(hasFocus)
//
        window.decorView.apply {
            // SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
            // a general rule, you should design your app to hide the status bar whenever you
            // hide the navigation bar.
//            systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
            systemUiVisibility  = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        }
    }
}

